<template>
    <el-menu
        class="navigation"
        mode="horizontal"
        :default-active="activeIndex"
        :ellipsis="false"
        unique-opened
        router
        @select="pageChangeHandler"
    >
        <!-- 主菜单 -->
        <el-menu-item class="logo" disabled>
            <span>GROUP FOUR在线书城</span>
        </el-menu-item>
        <el-menu-item index="/">首页</el-menu-item>
        <el-sub-menu index="/category">
            <template #title>图书类别</template>
            <el-menu-item
                v-for="item in categoryList"
                :key="item"
                :index="'/category?categoryID=' + item.categoryID + '&category=' + item.category"
            >
                {{ item.category }}
            </el-menu-item>
        </el-sub-menu>
        <el-menu-item index="/cart">购物车</el-menu-item>
        <el-menu-item index="/order">我的订单</el-menu-item>
        <el-menu-item index="/address">收货地址 </el-menu-item>
        <!-- 搜索框 -->
        <div style="flex-grow: 1"></div>
        <div class="searchInput">
            <el-autocomplete
                placeholder="搜索"
                :suffix-icon="searchIcon"
                v-model="searchText"
                :fetch-suggestions="fetchSuggestionsHandler"
                :trigger-on-focus="true"
                @select="detailHandler"
            />
        </div>
        <!-- 用户菜单 -->
        <div style="flex-grow: 1"></div>
        <!-- <el-menu-item index="/user/register" v-if="!isLogin">注册</el-menu-item> -->
        <el-menu-item index="/user/login" v-if="!isLogin">登录 / 注册</el-menu-item>
        <el-dropdown v-else class="loginUser">
            <div>
                您好，<span style="color: #1d2731; margin-right: 0.4rem; font-weight: bold">{{ username }}</span>
                <el-icon><arrow-down /></el-icon>
            </div>
            <template #dropdown>
                <el-dropdown-menu>
                    <el-dropdown-item v-for="item in userMenu" @click="userMenuHandler(item)" :key="item">
                        {{ item.title }}
                    </el-dropdown-item>
                    <el-dropdown-item @click="logoutHandler">注销</el-dropdown-item>
                </el-dropdown-menu>
            </template>
        </el-dropdown>
    </el-menu>
</template>

<script>
import store from "@/store";
import service from "@/utils/request";
import { ArrowDown, Search } from "@element-plus/icons-vue";
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import { markRaw } from "vue";

export default {
    name: "Navigation",
    data() {
        return {
            categoryList: [],
            searchIcon: markRaw(Search),
            activeIndex: "/",
            searchText: "",
            userMenu: [
                {
                    name: "personalInfo",
                    title: "个人信息",
                },
                {
                    name: "cart",
                    title: "我的购物车",
                },
                {
                    name: "order",
                    title: "我的订单",
                },
                {
                    name: "address",
                    title: "我的地址",
                },
            ],
            username: "",
            isLogin: false,
            recommendList: [],
        };
    },
    components: {
        ArrowDown,
    },
    methods: {
        detailHandler(e) {
            // console.log(e);
            this.$router.push(`/detail/${e.bookID}`);
            setTimeout(() => {
                window.location.reload();
            }, 200);
        },
        fetchSuggestionsHandler(queryString, callback) {
            let result = [];
            axios.get(`http://localhost:8088/bookmall/book/list/1/5?title=${queryString}`).then((res) => {
                // console.log(res.data);
                res.data.data.records.forEach((item) => {
                    result.push({ value: item.title, bookID: item.bookID });
                });
                callback(result);
            });
        },
        // 用户注销账号
        logoutHandler() {
            let _that = this;
            ElMessageBox.confirm("确认要注销吗", "警告", {
                confirmButtonText: "确认",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    ElMessage({
                        type: "success",
                        message: "注销成功，正在返回登录页",
                    });
                    store.commit("setActiveIndex", "user/login");
                    store.commit("logout");
                    setTimeout(() => {
                        window.location.reload();
                        _that.$router.replace({ name: "login" });
                    }, 200);
                })
                .catch(()=>{});
        },
        // 页面切换事件
        pageChangeHandler(path) {
            if (store.state.activeIndex !== path) {
                store.commit("setActiveIndex", path);
            }
            store.commit("getActiveIndex");
            this.activeIndex = store.state.activeIndex;
        },
        userMenuHandler(item) {
            this.$router.replace({ name: item.name });
            store.commit("setActiveIndex", "/" + item.name);
            store.commit("getActiveIndex");
            this.activeIndex = store.state.activeIndex;
        },
    },
    beforeMount() {
        service.get("/category/list").then((res) => {
            // console.log(res.data);
            this.categoryList = res.data;
        });
        // 检测用户登录状态
        store.commit("checkLogin");
        this.isLogin = store.state.isLogin;
        // console.log(this.isLogin);
        if (this.isLogin) {
            store.commit("setUserInfo");
            // 获取用户信息
            store.commit("getUserInfo");
            // console.log(store.state.userInfo);
            this.username = store.state.userInfo.username;
            store.commit("setActiveIndex", "/");
        }
        // 获取当前激活的页面路由
        store.commit("getActiveIndex");
        this.activeIndex = store.state.activeIndex;
    },
};
</script>

<style lang="scss" scoped>
.navigation {
    z-index: 999;
    padding: 0 20px;
    --el-menu-bg-color: #90caf9;
    --el-menu-active-color: #5c6bc0;
    box-shadow: 0 2px 10px lightgray;

    .logo {
        cursor: default;

        span {
            font-size: 1.2rem;
            font-weight: bold;
        }
    }

    .el-menu-item.is-disabled {
        opacity: 1;
    }

    .user {
        display: flex;
        flex-direction: row;
    }

    .loginUser {
        position: relative;
        align-items: center;
        cursor: default;
        margin-right: 0.5rem;
    }

    .searchInput {
        position: relative;
        width: 12rem;
        margin-top: 14px;
        height: 50%;
        align-items: center;
    }
}
</style>
